package me.shiqiang.im;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.aliyun.push20160801.Client;
import com.aliyun.teaopenapi.models.Config;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.protocol.JacksonJsonSupport;
import me.shiqiang.im.config.RocketMqConsumerConfig;
import me.shiqiang.im.config.RocketMqProducerConfig;
import me.shiqiang.im.linsteners.Listener;
import me.shiqiang.im.server.Auth;
import me.shiqiang.im.util.RedisPipelineProcessor;
import me.shiqiang.im.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import com.aliyun.tea.*;

import javax.annotation.Resource;
import javax.net.ssl.KeyManagerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

//@SpringCloudApplication
@EnableFeignClients
@EnableCaching
//@EnableAutoConfiguration
@SpringBootApplication
public class ImSocketioServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ImSocketioServerApplication.class, args);
    }

    @Bean
    public ConcurrentLinkedQueue<RedisPipelineProcessor> createQueue() {
        return new ConcurrentLinkedQueue<>();
    }

    @Value("${connect.port}")
    String port;

    @Value("${server.id}")
    String serverId;

    @Value("${server.machineId}")
    String machineId;

    @Value("${aliyun.accessKey}")
    String aliyunAccessKey;

    @Value("${aliyun.secret}")
    String aliyunSecret;



//    @Autowired
//    private Map<String, MessageListener> consumerMap;

//    @Resource
//    private Auth auth;

    @Value("#{${com.tst.rocketmq.consumer.subscription}}")
    Map<String, String> consumerSubscription;



    @Bean
    public SnowFlake createSnowFlake() {
        return new SnowFlake(Long.parseLong(serverId), Long.parseLong(machineId));
    }


    @Autowired
    private Map<String, Listener> listenerMap;


//    @Bean(initMethod = "start", destroyMethod = "shutdown")
//    public ConsumerBean createConsumerBean(RocketMqConsumerConfig config) {
//        ConsumerBean consumerBean = new ConsumerBean();
//        consumerBean.setProperties(config.getProperties());
//        Map<Subscription, MessageListener> table = new HashMap<>();
//        for (Map.Entry<String, MessageListener> entry : consumerMap.entrySet()) {
//            String[] keys = consumerSubscription.get(entry.getKey()).split("#");
//            Subscription subscription = new Subscription();
//            subscription.setTopic(keys[0]);
//            subscription.setExpression(keys[1]);
//            table.put(subscription, entry.getValue());
//        }
//        consumerBean.setSubscriptionTable(table);
//        return consumerBean;
//    }

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ProducerBean createProducerBean(RocketMqProducerConfig config) {
        ProducerBean producerBean = new ProducerBean();
        producerBean.setProperties(config.getProperties());
        return producerBean;
    }


    @Bean(initMethod = "start", destroyMethod = "stop")
    public SocketIOServer createServer() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        Configuration configuration = new Configuration();
//        configuration.setAuthorizationListener(auth);
//		configuration.setHostname("192.168.20.143");
//        configuration.setAuthorizationListener(auth);
        configuration.setPort(Integer.parseInt(port));

        configuration.setKeyStorePassword("Nbb@123.");
        InputStream stream = ImSocketioServerApplication.class.getResourceAsStream("/keystore.jks");
        configuration.setKeyStore(stream);


        SocketConfig socketConfig = configuration.getSocketConfig();
        socketConfig.setReuseAddress(true);//添加此配置，解决重启报 Address already in use异常
        JacksonJsonSupport jacksonJsonSupport = new JacksonJsonSupport();
        configuration.setJsonSupport(jacksonJsonSupport);

        SocketIOServer server = new SocketIOServer(configuration);
        for (Listener listener : listenerMap.values()) {
            listener.setServer(server);
            server.addListeners(listener);
        }
        return server;
    }

    @Bean
    public Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(aliyunAccessKey)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(aliyunSecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Push
        config.endpoint = "cloudpush.aliyuncs.com";
        return new com.aliyun.push20160801.Client(config);
    }
}
